import os
import sys
import socket
import subprocess

def check_file_exists(filepath, description):
    exists = os.path.exists(filepath)
    print(f"[{'✓' if exists else '✗'}] {description}: {filepath}")
    return exists

def check_port_in_use(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(('127.0.0.1', port))
    sock.close()
    in_use = result == 0
    print(f"[{'✓' if in_use else '✗'}] Port {port} is {'in use' if in_use else 'not in use'}")
    return in_use

def check_process_running(process_name):
    try:
        output = subprocess.check_output(['pgrep', '-f', process_name])
        running = bool(output)
    except subprocess.CalledProcessError:
        running = False
    print(f"[{'✓' if running else '✗'}] Process {process_name} is {'running' if running else 'not running'}")
    return running

def check_file_permissions(filepath, required_permissions):
    if not os.path.exists(filepath):
        print(f"[✗] File does not exist: {filepath}")
        return False
    
    current_permissions = oct(os.stat(filepath).st_mode)[-3:]
    matches = current_permissions == str(required_permissions)
    print(f"[{'✓' if matches else '✗'}] Permissions for {filepath}: {current_permissions} (required: {required_permissions})")
    return matches

def main():
    project_root = "/www/wwwroot/spvi.lingbankeji.com"
    
    print("\n=== Checking Files ===")
    files_to_check = {
        'wsgi.py': 'WSGI入口文件',
        'uwsgi.ini': 'uWSGI配置文件',
        'app/static/favicon.ico': 'Favicon文件',
        '.env': '环境配置文件'
    }
    
    for file, desc in files_to_check.items():
        check_file_exists(os.path.join(project_root, file), desc)
    
    print("\n=== Checking Processes ===")
    check_process_running('uwsgi')
    check_process_running('nginx')
    
    print("\n=== Checking Ports ===")
    check_port_in_use(8000)  # uwsgi
    check_port_in_use(80)    # nginx
    
    print("\n=== Checking Permissions ===")
    dirs_to_check = [
        (os.path.join(project_root, 'app/static'), 755),
        (os.path.join(project_root, 'instance'), 777),
        (os.path.join(project_root, 'logs'), 777)
    ]
    
    for dir_path, perms in dirs_to_check:
        check_file_permissions(dir_path, perms)
    
    print("\n=== Checking Nginx Configuration ===")
    try:
        nginx_test = subprocess.run(['nginx', '-t'], capture_output=True, text=True)
        print(f"[{'✓' if nginx_test.returncode == 0 else '✗'}] Nginx configuration test")
        if nginx_test.stderr:
            print(nginx_test.stderr)
    except Exception as e:
        print(f"[✗] Error testing nginx configuration: {e}")

if __name__ == "__main__":
    main() 